import { login, logout, getInfo } from '@/api/user'
import {
  getName, getAvatar, getToken, getUserID, getUserSig, getRouter, getFunctionId,
  setName, setAvatar, setToken, setUserID, setUserSig, setRouter,
  removeRouter, removeToken, removeName, removeAvatar, removeUserID, removeUserSig, removeFunctionId
} from '@/utils/auth'
import router, { resetRouter } from '@/router'
import { Message } from 'element-ui'
import store from '@/store'

const getDefaultState = () => {
  return {
    token: getToken(),
    name: getName(),
    avatar: getAvatar(),
    userID: getUserID(),
    roles: getRouter(),
    functionId: getFunctionId()
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_USER_ID: (state, id) => {
    state.userID = id
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  setFunctionId: (state, id) => {
    state.functionId = id
  }
}

const actions = {
  // user login
  login({ commit, dispatch }, userInfo) {
    return new Promise((resolve, reject) => {
      login({ userName: userInfo.username, password: userInfo.password }).then(async response => {
        const { token, data: { userName, imgUrl, userId: userID }, list, data } = response

        console.log(response)
        var roles = list.filter(list => !list.hidden)
        if (roles.length === 0) {
          Message.error('您当前没有权限去任何页面，请联系管理员添加')
          reject('/404')
        }
        setName(userName)
        setAvatar(imgUrl)
        setToken(token)
        setUserID(userID)
        setRouter(roles)

        // 设置store
        commit('SET_NAME', userName)
        commit('SET_AVATAR', imgUrl)
        commit('SET_TOKEN', token)
        commit('SET_USER_ID', userID)
        commit('SET_ROLES', roles)

        // 设置路由routes
        await store.dispatch('permission/generateRoutes', roles)

        setTimeout(() => {
          resolve()
        }, 0)
      }).catch(error => {
        console.info(error)
        reject(error)
      })
    })
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token).then(response => {
        const { data } = response

        if (!data) {
          return reject('Verification failed, please Login again.')
        }

        const { name, avatar } = data

        commit('SET_NAME', name)
        commit('SET_AVATAR', avatar)
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, state, dispatch }) {
    return new Promise((resolve, reject) => {
      logout({ token: state.token }).then(async() => {
        await dispatch('resetToken')
        resolve()
      }).catch(async error => {
        await dispatch('resetToken')
        resolve(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      removeName()
      removeAvatar()
      removeUserID()
      removeUserSig()
      removeFunctionId()
      removeRouter()

      resetRouter()
      commit('RESET_STATE')
      router.replace('/login')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

